# coding=utf-8
# 全世界最帅的帅哥
import json

from flask import request, g
from flask_jwt_extended import verify_jwt_in_request, get_jwt_identity

from ysgg1_club_comment.constant.redis_prefix import RedisPrefix
from ysgg1_club_comment.redis_client import redis_client


def login_filter():
    flag = False

    def wrapper():
        nonlocal flag
        if verify_jwt_in_request(refresh=True):
            # 鉴权逻辑
            current_user = get_jwt_identity()
            g.token = current_user
            if request.method == "GET":
                flag = True
                return

            key = RedisPrefix.AUTH_PERMISSION_PREFIX + "." + current_user
            permission_bytes_json = redis_client.get(key)
            permission_list = json.loads(permission_bytes_json.decode())
            method = request.method
            permission = "subject" + ":" + method.lower()
            for permission_info in permission_list:
                if permission == permission_info["permission_key"]:
                    flag = True
                    return

    wrapper()

    if not flag:
        return {"code": 401, "message": "you don't have permission"}